<?php
namespace app\apijson\query;

use app\apijson\query\operators\ColumnOperator;
use app\apijson\query\operators\OrderOperator;
use app\apijson\query\operators\GroupOperator;
use app\apijson\query\operators\BetweenOperator;
use app\apijson\query\operators\InOperator;
use app\apijson\query\operators\WhereRawOperator;
use app\apijson\query\operators\WithOperator;
use app\apijson\query\operators\WhereHasOperator;
use app\apijson\query\operators\JsonOperator;
use app\apijson\query\operators\LikeOperator;
use app\apijson\query\operators\LogicOperator;
use app\apijson\query\operators\ReferenceOperator;
use app\apijson\query\operators\LimitOperator;

class OperatorHandler
{
    public static function apply($query, $key, $value, $parentData = [])
    {
        if ($key[0] === '@') {
            // 字段筛选、排序、分组等
            if ($key === '@column') {
                ColumnOperator::apply($query, $value);
            } elseif ($key === '@order') {
                OrderOperator::apply($query, $value);
            } elseif ($key === '@group') {
                GroupOperator::applyGroup($query, $value);
            } elseif ($key === '@having') {
                GroupOperator::applyHaving($query, $value);
            } elseif ($key === '@between') {
                BetweenOperator::apply($query, $value);
            } elseif ($key === '@in') {
                InOperator::apply($query, $value);
            } elseif ($key === '@whereRaw') {
                WhereRawOperator::apply($query, $value);
            } elseif ($key === '@with') {
                WithOperator::apply($query, $value);
            } elseif ($key === '@whereHas') {
                WhereHasOperator::apply($query, $value);
            } elseif ($key === '@limit') {
                LimitOperator::apply($query, $value);
            }
            return;
        }

        // JSON 查询
        if (JsonOperator::apply($query, $key, $value)) {
            return;
        }

        // 模糊查询
        if (LikeOperator::apply($query, $key, $value)) {
            return;
        }

        // 逻辑运算符
        if (LogicOperator::apply($query, $key, $value)) {
            return;
        }

        // 引用操作符
        if (ReferenceOperator::apply($query, $key, $value, $parentData)) {
            return;
        }

        // 普通字段
        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $key)) {
            throw new \app\apijson\core\ApiJsonException('非法字段名: ' . $key);
        }
        $query->where($key, $value);
    }

    public static function getAliasMap($query)
    {
        return ColumnOperator::getAliasMap($query);
    }
} 